<template>
  <div id="Login">
    <el-dialog
      title="登录"
      :visible="dialogFormVisible"
      width="430px"
      :before-close="closeDialog"
    >
      <el-form ref="ruleForm" :model="form" label-width="80px" :rules="rules">
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="form.password" show-password></el-input>
        </el-form-item>
        <span style="color: #c20c0c; text-align: center">{{
            form.errMsg
          }}</span>
        <el-form-item>
          <el-button type="primary" style="width: 100px" @click.stop="onSubmit"
          >登录
          </el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Login",
  data() {
    // 手机号检验规则
    let validatePhone = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入手机号"));
      } else {
        if (/^1[3456789]\d{9}$/.test(value)) {
          callback();
        } else {
          callback(new Error("请输入正确手机号"));
        }
      }
    };
    // 密码检验规则
    let validatePassword = (rule, value, callback) => {
      if (value === "") {
        return callback(new Error("请输入密码"));
      } else {
        callback();
      }
    };

    return {
      // 表单数据
      form: {
        phone: "",
        password: "",
        errMsg: "",
      },
      rules: {
        phone: [{validator: validatePhone, trigger: "blur", required: true}],
        password: [
          {validator: validatePassword, trigger: "blur", required: true},
        ],
      },
    };
  },
  props: ["dialogFormVisible"],
  methods: {
    closeDialog() {
      this.$emit("update:dialogFormVisible", false);
    },
    onSubmit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          // 检验通过 派发action
          this.$store.dispatch("userLogin", this.form).then(() => {
            this.$emit("update:dialogFormVisible", false);
          });
        } else {
          return false;
        }
      });
    },
  },
};
</script>

<style scoped lang='less'>
</style>